package com.glodon.paas.account.security.cas.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;

import com.glodon.paas.account.security.spring.LoginUser;

/**
 * @author Don Li
 */
public class AutoLoginFilter implements Filter {
    public static final String AUTO_LOGIN_USER = "AUTO_LOGIN_USER";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest httpReq = (HttpServletRequest) request;

        LoginUser user = (LoginUser) httpReq.getSession().getAttribute(AUTO_LOGIN_USER);
        if (user != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            httpReq.getSession(false).removeAttribute(AUTO_LOGIN_USER);

            List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(1);
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(), authorities);
            authentication.setDetails(new WebAuthenticationDetails(httpReq));

            SecurityContextHolder.clearContext();
            SecurityContextHolder.getContext().setAuthentication(authentication);
            httpReq.getSession(false).setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());

            chain.doFilter(request, response); // redirect to home page
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
    }
}
